<?php
/**
 * Created by Dumitru Russu
 * User: developer
 * Date: 9/3/12
 * Time: 4:12 PM
 * To change this template use File | Settings | File Templates.
 */
class Db_Accounts_Permissions extends Common {
    protected static $tableName = TAB_PERMISSIONS;
    protected static $dbFields = array(
        'id',
        'pm_identifier',
        'pm_parent_id',
        'deleted'
    );

    public $id;
    public $pm_identifier;
    public $pm_parent_id;
    public $deleted;

    function __construct($value=NULL, $fieldName=NULL) {
        parent::__construct($value, $fieldName);
    }

    public static function getAllPermissions(){
        $permissions = array();
        $allPermissions = self::$DB->q("SELECT * FROM ?f WHERE `deleted` = 0;", self::$tableName);

        while($data = $allPermissions->fetch_assoc()) {
            if(!$data['pm_parent_id']) {
                $permissions[$data['id']] = array(
                    'constant' => $data['pm_identifier'],
                    'childrens' => array()
                );
            } else {
                $permissions[$data['pm_parent_id']]['childrens'][$data['id']] = $data['pm_identifier'];
            }
        }
        return $permissions;
    }

    public static function abstractDeletePermissions($permissionId) {
        $permissions  = self::$DB->q('SELECT * FROM ?f WHERE `pm_parent_id` = ?d AND `deleted` = 0 ;', self::$tableName, $permissionId);

        if($permissions->num_rows > 0) {
            self::$DB->q('UPDATE ?f SET `deleted` = 1 WHERE `pm_parent_id` = ?d AND `deleted` = 0;', self::$tableName, $permissionId);
            return (self::$DB->mysqlModifiedRows() > 0 ? true : false );
        } else {
            return true;
        }
    }

    /**
     * Method getCurrentUserPermissions return user Permissions by user ID
     *
     * @static
     * @return array|bool
     */
    public static function getCurrentUserPermissions() {

		$permissions = unserialize(self::$USER['ug_permissions']);
		$useAllPermissions = array();
		$allPermissions =  self::$DB->q('SELECT `id`, `pm_identifier` FROM ?f WHERE `deleted` = 0;', self::$tableName);

		while($data = $allPermissions->fetch_assoc()) {
			$useAllPermissions[$data['id']] = $data['pm_identifier'];
		}

		$usePermissions = array();
		foreach($permissions as $permissionId => $value) {
			if (isset($useAllPermissions[$permissionId])) {
				$usePermissions[$useAllPermissions[$permissionId]] = true;
			}
		}
		return $usePermissions;
    }
}
